package com.up.cloudfeiyibackend.service.impl;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.up.cloudfeiyibackend.constant.InheritorMessageConstant;
import com.up.cloudfeiyibackend.dto.InheritorApplicationDto;
import com.up.cloudfeiyibackend.entity.*;
import com.up.cloudfeiyibackend.exception.InheritorAppliedException;
import com.up.cloudfeiyibackend.mapper.InheritorMapper;
import com.up.cloudfeiyibackend.mapper.ItemMapper;
import com.up.cloudfeiyibackend.mapper.UserMapper;
import com.up.cloudfeiyibackend.result.Result;
import com.up.cloudfeiyibackend.service.InheritorService;
import com.up.cloudfeiyibackend.service.ItemService;
import com.up.cloudfeiyibackend.util.UserHolder;
import com.up.cloudfeiyibackend.vo.InheritorApplicationVO;
import com.up.cloudfeiyibackend.vo.InheritorVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class InheritorServiceImpl implements InheritorService {

    private final InheritorMapper inheritorMapper;

    private final ObjectMapper objectMapper;
    private final UserMapper userMapper;

    private final ItemService itemService;
    private final ItemMapper itemMapper;

    /**
     * 申请非遗传承人
     *
     * @param inheritorApplicationDto
     */
    @Override
    public void apply(InheritorApplicationDto inheritorApplicationDto) {
        // 获取当前用户ID

        Long userId = UserHolder.get();
        // 检查用户是否已经申请
        int count = inheritorMapper.checkUserApplied(userId, inheritorApplicationDto.getItemId());
        if (count > 0) {
            throw new InheritorAppliedException(InheritorMessageConstant.ALREADY_APPLIED);
        }

        // 处理相关数据
        InheritorApplication inheritorApplication = new InheritorApplication();
        BeanUtils.copyProperties(inheritorApplicationDto, inheritorApplication);
        // 处理佐证材料（多图片URL）
        if (inheritorApplicationDto!= null){
            List<String> proofMaterials = inheritorApplicationDto.getProofMaterials();
            try {
                String s = objectMapper.writeValueAsString(proofMaterials);
                inheritorApplication.setProofMaterials(s);

            } catch (JsonProcessingException e) {
                throw new RuntimeException("佐证材料（多图片URL）格式转换失败，请检查图片URL格式", e);
            }
        }
        inheritorApplication.setUserId(userId);
        inheritorApplication.setStatus(0);
        inheritorApplication.setCreatedAt(LocalDateTime.now());
        inheritorApplication.setUpdatedAt(LocalDateTime.now());
        // 插入申请记录
        inheritorMapper.insertApplication(inheritorApplication);
    }

    /**
     * 获取用户申请列表
     *
     * @return
     */
    @Override
    public List<InheritorApplicationVO> getUserApplications() {
        // 获取当前用户ID
        Long userId = UserHolder.get();

        // 查询用户申请记录
        List<InheritorApplication> inheritorApplicationList = inheritorMapper.getApplicationsByUserId(userId);

        List<InheritorApplicationVO> inheritorApplicationVOS = new ArrayList<>();
        for (InheritorApplication inheritorApplication : inheritorApplicationList) {
            Long itemId = inheritorApplication.getItemId();
            Item itemByItemId = itemMapper.getItemByItemId(itemId);
            InheritorApplicationVO inheritorApplicationVO = new InheritorApplicationVO();
            BeanUtils.copyProperties(inheritorApplication, inheritorApplicationVO);
            inheritorApplicationVO.setItemName(itemByItemId.getName());
            if (inheritorApplication.getProofMaterials() != null) {
                String proofMaterials = inheritorApplication.getProofMaterials();
                List<String> list = JSONUtil.toList(proofMaterials, String.class);
                inheritorApplicationVO.setProofMaterials(list);
            }
            inheritorApplicationVOS.add(inheritorApplicationVO);
        }
        return inheritorApplicationVOS;
    }


    /**
     *
     * 获取当前用户的非遗传承人信息
     * @return
     */
    @Override
    public Result<InheritorVO> getMyInheritor() {
        Long userId = UserHolder.get();

       Inheritor inheritor =  inheritorMapper.getMyInheritor(userId);
       if (inheritor == null){
           return Result.error(InheritorMessageConstant.NO_INHERITOR_INFORMATION);
       }
       User user =   userMapper.findById(userId);
       Item item =   itemMapper.getItemByItemId(inheritor.getItemId());
       InheritorVO inheritorVO = new InheritorVO();
       inheritorVO.setItemName(item.getName());
       BeanUtils.copyProperties(inheritor, inheritorVO);
       if (inheritor.getProofMaterials() != null){
           String proofMaterials = inheritor.getProofMaterials();
           List<String> list = JSONUtil.toList(proofMaterials, String.class);
           inheritorVO.setProofMaterials(list);
       }
       return Result.success(InheritorMessageConstant.GET_INFORMATION_SUCCESS,inheritorVO);
    }




}
